<template>
  <div class="login-form-wrapper" @click.stop>
    <div class="login-form-title">后台系统登录</div>
<!--    <div class="login-form-sub-title">{{ $t('login.form.title') }}</div>-->
    <div class="login-form-error-msg">{{ errorMessage }}</div>
    <a-form
      ref="loginForm"
      :model="formModel"
      class="login-form"
      layout="vertical"
      @submit="handleSubmit"
    >
      <a-form-item
        field="username"
        :rules="[{ required: true, message: $t('login.form.userName.errMsg') }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input v-model="formModel.username" :size="size" allow-clear>
          <template #prefix>
            <icon-user />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
        field="password"
        :rules="[{ required: true, message: $t('login.form.password.errMsg') }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input-password v-model="formModel.password" :size="size" allow-clear>
          <template #prefix>
            <icon-lock />
          </template>
        </a-input-password>
      </a-form-item>
      <a-form-item v-if="captcha.captcha_switch" field="captcha_code" hide-label>
        <a-row :gutter="8">
          <a-col :span="12">
            <a-input v-model="formModel.captcha_code" :size="size" allow-clear>
              <template #prefix>
                <icon-check-square />
              </template>
            </a-input>
          </a-col>
          <a-col :span="12">
            <a-image :src="captcha.captcha_src" alt="" title="" width="100%" :preview="false" style="cursor: pointer;" @click="getCaptcha"/>
          </a-col>
        </a-row>
      </a-form-item>
      <a-form-item hide-label>
        <a-button type="outline" long @click="handleSlideVerify"><icon-safe style="margin-right: 20px;"/>点击验证</a-button>
      </a-form-item>
<!--      <div v-if="slideVerifyVisible === true" class="slide-verify-mask">
        <slide-verify
          ref="slideVerifyRef"
          :l="42"
          :r="10"
          :w="320"
          :h="155"
          slider-text="向右滑动完成验证"
          :imgs="sliderImgs"
          @success="verifySuccess"
          @fail="verifyFail"
        />
      </div>-->
      <div v-if="slideVerifyVisible === true">
        <slide-puzzle-verify
          ref="slideVerifyRef"
          :imgs="sliderImgs"
          @success="verifySuccess"
          @fail="verifyFail"
          @close="verifyClose"
        />
      </div>
      <a-space :size="16" direction="vertical">
        <div class="login-form-password-actions">
          <a-checkbox
            checked="rememberPassword"
            v-model="formModel.remember"
            @change="setRememberPassword as any"
          >
            {{ $t('login.form.rememberPassword') }}
          </a-checkbox>
<!--          <a-link>{{ $t('login.form.forgetPassword') }}</a-link>-->
        </div>
        <a-button type="primary" html-type="submit" long :disabled="disabledSubmit" :loading="loading">
          {{ $t('login.form.login') }}
        </a-button>
<!--        <a-button type="text" long class="login-form-register-btn">-->
<!--          {{ $t('login.form.register') }}-->
<!--        </a-button>-->
      </a-space>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import { useI18n } from 'vue-i18n';
  import { useStorage } from '@vueuse/core';

  import { useAdminStore } from '@/store';
  import useLoading from '@/hooks/loading';
  import { apiCaptcha } from '@/api/common';
  import type { LoginData } from '@/api/admin';
  // import SlideVerify from '@/components/verify/slide-puzzle01/index.vue';
  import SlidePuzzleVerify from '@/components/verify/slide-puzzle/index.vue';
  import SlideVerifyImg1 from '@/assets/verify/slide-puzzle1.png';
  import SlideVerifyImg2 from '@/assets/verify/slide-puzzle2.png';
  import SlideVerifyImg3 from '@/assets/verify/slide-puzzle3.png';
  import SlideVerifyImg4 from '@/assets/verify/slide-puzzle4.png';
  import SlideVerifyImg5 from '@/assets/verify/slide-puzzle5.png';

  const router = useRouter();
  const { t } = useI18n();
  const errorMessage = ref('');
  const { loading, setLoading } = useLoading();
  const userStore = useAdminStore();

  const loginConfig = useStorage('login-config', {
    rememberPassword: true,
    username: '',
    password: '',
  });
  const formModel = reactive({
    username: loginConfig.value.username,
    password: loginConfig.value.password,
    remember: loginConfig.value.rememberPassword,
    captcha_key: '',
    captcha_code: '',
  });
  const size = ref<any>('large');
  const captcha = ref({
    captcha_switch: 0,
    captcha_src: '',
  });

  // 滑动拼图验证
  const sliderImgs = [
    SlideVerifyImg1,
    SlideVerifyImg2,
    SlideVerifyImg3,
    SlideVerifyImg4,
    SlideVerifyImg5,
  ];
  const slideVerifyVisible = ref(false);
  const disabledSubmit = ref(true);

  // 字符验证码
  const getCaptcha = async () => {
    const { data } = await apiCaptcha({});
    if (data.switch) {
      captcha.value.captcha_switch = data.switch;
      captcha.value.captcha_src = data.src;
      formModel.captcha_key = data.key;
    }
  };
  // 登录
  const handleSubmit = async ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined;
    values: Record<string, any>;
  }) => {
    if (loading.value) {
      return;
    }
    if (!errors) {
      setLoading(true);
      try {
        await userStore.login(values as LoginData);
        const { redirect, ...othersQuery } = router.currentRoute.value.query;
        router.push({
          name: (redirect as string) || 'Dashboard',
          query: {
            ...othersQuery,
          },
        });
        Message.success(t('login.form.login.success'));
        const { rememberPassword } = loginConfig.value;
        const { username, password } = values;
        // 实际生产环境需要进行加密存储。
        // The actual production environment requires encrypted storage.
        loginConfig.value.username = rememberPassword ? username : '';
        loginConfig.value.password = rememberPassword ? password : '';
      } catch (err) {
        errorMessage.value = (err as Error).message;
        getCaptcha();
      } finally {
        setLoading(false);
      }
    }
  };
  const setRememberPassword = (value: boolean) => {
    loginConfig.value.rememberPassword = value;
  };

  const handleSlideVerify = () => {
    slideVerifyVisible.value = true;
  };
  const verifySuccess = (times: number) => {
    // const msg = `验证成功, 耗时${(times / 1000).toFixed(1)}s`;
    // Message.success(msg);
    slideVerifyVisible.value = false;
    disabledSubmit.value = false;
  };
  const verifyFail = () => {
    // 验证不通过
  };
  const verifyClose = () => {
    slideVerifyVisible.value = false;
  };

  getCaptcha();
</script>

<style lang="less" scoped>
  .login-form {
    &-wrapper {
      width: 360px;
    }

    &-title {
      color: var(--color-text-1);
      font-weight: 500;
      font-size: 24px;
      line-height: 32px;
    }

    &-sub-title {
      color: var(--color-text-3);
      font-size: 16px;
      line-height: 24px;
    }

    &-error-msg {
      height: 32px;
      color: rgb(var(--red-6));
      line-height: 32px;
    }

    &-password-actions {
      display: flex;
      justify-content: space-between;
    }

    &-register-btn {
      color: var(--color-text-3) !important;
    }
  }

  .login-form-wrapper {
    background-color: #fff;
    border-radius: 1em;
    border: 1px solid #fff;
    padding: 20px;
  }
  .login-form-wrapper .login-form-title {
    text-align: center;
  }
  .slide-verify-mask {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1001;
    width: 100%;
    height: 100vh;
    background: rgba(0,0,0,.3);
    -webkit-transition: all .5s;
    transition: all .5s;
  }
  .slide-verify-mask .slide-verify {
    position: relative;
    box-sizing: border-box;
    border-radius: 2px;
    border: 1px solid #e4e7eb;
    background-color: #fff;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
    left: 50%;
    top: 445px;
    transform: translate(-50%, -50%);
  }
</style>
